﻿package	birdry.font	{
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.EventDispatcher;
	import flash.system.Security;
	import flash.system.SecurityDomain;
	import flash.system.ApplicationDomain; 
	import flash.system.LoaderContext;
	import flash.display.Loader;
	import flash.net.URLRequest;
	import flash.text.Font;
	import flash.utils.getQualifiedClassName;
	import flash.text.FontType;
	
	public class FontLoader	extends EventDispatcher	{
		
		public static const FONT_LOAD_PROGRESS:String = "progress";
		public static const FONT_LOAD_COMPLETE:String = "complete";
		
		private var _fontName:String;
		private var _fontUrl:String;
		
		private var _loader:Loader;
		
		public function get fontName(): String		{			
			return _fontName;		
		}
		
		public function FontLoader(fontUrl:String): void	{
			_fontUrl = fontUrl;
			
			var c:LoaderContext = new LoaderContext; 
			c.applicationDomain = new ApplicationDomain( ApplicationDomain.currentDomain ); 
			if ( Security.sandboxType == Security.REMOTE )	c.securityDomain = SecurityDomain.currentDomain; 
			
			_loader = new Loader();
			_loader.load( new URLRequest(_fontUrl), c );
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener);
		}
		
		private function progressListener(e: ProgressEvent): void	{
			dispatchEvent( e );
		}
		
		private function completeListener(e: Event): void	 {
			var font:Font = e.target.content.font;
			_fontName = font.fontName;
			
			
			/*	IDE로 만든 SWF 적용시
			var fontClass:Class = e.target.applicationDomain.getDefinition("FontClass") as Class;
			Font.registerFont(fontClass);
			var font:Font = new fontClass();
			_fontName = font.fontName;
			*/
			
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, completeListener);
			_loader.unload();
			_loader = null;
			dispatchEvent( new Event( FontLoader.FONT_LOAD_COMPLETE ));
		}
	}
}